package com.heartech.prediciton_wx.service.message;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class XmlConvertService {
    /* 解析xml */
    public Map<String, String> parseXml(HttpServletRequest request) throws IOException, DocumentException {
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<>();

        try (InputStream inputStream = request.getInputStream()) {
            // 读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();
            // 遍历所有子节点
            for (Element e : elementList) {
                map.put(e.getName(), e.getText());
                log.info("name：" + e.getName() + "   value：" + map.get(e.getName()));
                System.out.println("name：" + e.getName() + "   value：" + map.get(e.getName()));
            }
        } catch (IOException | DocumentException e) {
            // 异常处理，可以根据具体情况选择是否抛出自定义异常
            log.error("Error while parsing XML: " + e.getMessage());
            throw e;
        }
        return map;
    }


}
